package com.xzxy.xmlg_backend.utils;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.xzxy.xmlg_backend.entity.Class;
import com.xzxy.xmlg_backend.entity.Emp;
import com.xzxy.xmlg_backend.entity.Result;
import com.xzxy.xmlg_backend.entity.Student;
import com.xzxy.xmlg_backend.service.IClassService;
import com.xzxy.xmlg_backend.service.IEmpService;
import com.xzxy.xmlg_backend.service.IStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Component
public class FileUploadUtils {

    // 头像保存路径
    @Value("${file.avatarPath}")
    private String avatarPath;

    @Autowired
    private IClassService iClassService;

    @Autowired
    private IEmpService empService;

    @Autowired
    private IStudentService studentService;

    /**
     * 上传头像
     * @param file 头像文件
     * @return 头像访问URL
     */
    public Result uploadAvatar(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("上传失败，请选择文件");
        }

        // 获取项目根目录
        String projectPath = System.getProperty("user.dir");
        // 头像存储的完整路径
        String avatarDir = projectPath + File.separator + avatarPath;

        // 确保目录存在
        File dir = new File(avatarDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 生成文件名
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;

        // 保存文件
        try {
            file.transferTo(new File(avatarDir + File.separator + fileName));
            System.out.println(avatarDir + File.separator + fileName);
            // 返回访问URL
            String fileUrl = "/avatar/" + fileName;
            return Result.success(fileUrl);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail("上传失败：" + e.getMessage());
        }
    }

    /**
     * 班级批量导入
     * @param file
     * @return
     */
    public Result uploadClass(MultipartFile file){
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<Class> classList = null;
        try {
            classList = ExcelImportUtil.importExcel(file.getInputStream(),Class.class,params);
        }catch (Exception E){
            System.out.println("导入班级任务失败:"+ E.getMessage());
            return Result.fail("导入班级任务失败:" + E.getMessage());
        }

        if (classList == null || classList.isEmpty()) {
            return Result.fail("未读取到班级数据或文件内容为空，请检查文件内容");
        }

        // 查询所有已有班级名称
        List<String> existingNames = iClassService.list().stream().map(x->x.getName()).toList(); // SELECT name FROM class;

        // 过滤掉已存在的班级
        List<Class> filteredList = classList.stream()
                .filter(clazz -> !existingNames.contains(clazz.getName()))
                .toList();
        if (filteredList.isEmpty()) {
            return Result.fail("所有班级已存在，无需导入");
        }
        boolean b = iClassService.saveBatch(filteredList);
        return b ? Result.success("导入成功!") : Result.fail("导入失败");
    }

    /**
     * 员工批量导入
     * @param file
     * @return
     */
    public Result uploadEmp(MultipartFile file){
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<Emp> empList = null;
        try {
            empList = ExcelImportUtil.importExcel(file.getInputStream(),Emp.class,params);
        }catch (Exception E){
            System.out.println("导入员工任务失败:"+ E.getMessage());
        }
        // 查询所有已有班级名称
        List<String> existingNames = empService.list().stream().map(x->x.getUsername()).toList(); // SELECT username FROM emp;

        // 过滤掉已存在的班级
        List<Emp> filteredList = empList.stream()
                .filter(emp -> !existingNames.contains(emp.getUsername()))
                .toList();
        if (filteredList.isEmpty()) {
            return Result.fail("所有用户名已存在，无需导入");
        }
        boolean b = empService.saveBatch(filteredList);
        return b ? Result.success("导入成功!") : Result.fail("导入失败");
    }

    /**
     * 学员批量导入
     * @param file
     * @return
     */
    public Result uploadStudent(MultipartFile file){
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        List<Student> studenList = null;
        try {
            studenList = ExcelImportUtil.importExcel(file.getInputStream(),Student.class,params);
        }catch (Exception E){
            System.out.println("导入员工任务失败:"+ E.getMessage());
        }
        // 查询所有已有班级名称
        List<String> existingStudentNos = studentService.list().stream().map(x->x.getStudentNo()).toList();

        // 过滤掉已存在的班级
        List<Student> filteredList = studenList.stream()
                .filter(emp -> !existingStudentNos.equals(emp.getStudentNo()))
                .toList();
        if (filteredList.isEmpty()) {
            return Result.fail("所有学号已存在，无需导入");
        }
        boolean b = studentService.saveBatch(filteredList);
        return b ? Result.success("导入成功!") : Result.fail("导入失败");
    }

}
